import com.mysql.cj.jdbc.CallableStatement;
import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description :
 * User: jiume
 * Date: 2024-09-28
 * Time: 21:59
 */
public class JDBC_Demo3 {
    public static void main(String[] args) {
        // 定义mysql数据源对象
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        // 设置数据连接串
        // URL
        mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/java?characterEncoding=utf8" +
                "&allowPublicKeyRetrieval=true&useSSL=false");
        // 用户名
        mysqlDataSource.setUser("root");
        // 密码
        mysqlDataSource.setPassword("123456");

        // 上面是厂商给我们提供的实现类，我们要使用Java层面的数据源接口
        DataSource dataSource = mysqlDataSource;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            // 建立连接
            connection = dataSource.getConnection();
            // 定义SQL并进行预编译
            String sql = "insert into student values (?,?,?,?)";
            preparedStatement = connection.prepareStatement(sql);
            // 接收输入
            Scanner scanner = new Scanner(System.in);
            System.out.print("请输入新增学生编号：");
            long id = Long.parseLong(scanner.next());
            System.out.print("请输入新增学生姓名：");
            String name = scanner.next();
            System.out.print("请输入新增学生年龄：");
            int age = Integer.parseInt(scanner.next());
            System.out.print("请输入新增学生性别：");
            byte gender = Byte.parseByte(scanner.next());
            // 替换占位符
            preparedStatement.setLong(1,id);
            preparedStatement.setString(2, name);
            preparedStatement.setInt(3,age);
            preparedStatement.setByte(4,gender);
            // 执行SQL语句，并接收结果集
            int line = preparedStatement.executeUpdate(); // 这里返回的是受影响的行数
            if (line == 1) {
                System.out.println("新增成功！");
            } else {
                System.out.println("新增失败！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 依次关闭资源
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}
